<script setup lang="ts">

import {defineProps, onMounted, ref, watch} from "vue";
import router from "@/router";
import {ElLoading, ElMessage} from "element-plus";

let user_key = ref('');
let isLoggedIn = ref(false);

interface user_info {
  money: string;
  last_logout_time: string;
  rank:string;
  vaild_time:string,
  name:string,
  pic:string,
}

const user_info_Data = ref<user_info[]>([]);

const check_init = () =>
{
  user_key = ref(localStorage.getItem('key'));
  if(user_key.value!=null)
  {
    isLoggedIn.value=true;
  }
  else
  {
    user_info_Data.value['name']="请先登录";
    user_info_Data.value['money']='';
    user_info_Data.value['last_logout_time']='';
    user_info_Data.value['rank']='';
    user_info_Data.value['vaild_time']='';
    user_info_Data.value['pic']='/nullaccimg.jpg';
    isLoggedIn.value=false;
  }
}

// const check_init2 = () =>
// {
//   if(isLoggedIn.value==false)
//   {
//
//     user_info_Data.value['name']="请先登录";
//     user_info_Data.value['money']='';
//     user_info_Data.value['last_logout_time']='';
//     user_info_Data.value['rank']='';
//     user_info_Data.value['vaild_time']='';
//     user_info_Data.value['pic']='/nullaccimg.jpg';
//   }
// }
//
//
const props = defineProps({
  key: {
    type: Boolean,
    required: true, // 将 prop 标记为必需的
  },
});

const get_user_info = async () =>
{
  try {
    const formData = new FormData();
    // Append any form fields you want to send
    formData.append('key',localStorage.getItem('key'));

    const response = await fetch('https://movie.cpb2013.top/account.php?mode=info',{method: 'POST',body:formData});
    const data = await response.json();
    user_info_Data.value['name']=data[0].name;
    user_info_Data.value['money']=data[0].money;
    user_info_Data.value['last_logout_time']=data[0].last_logout_time;
    user_info_Data.value['rank']=data[0].rank;
    user_info_Data.value['vaild_time']=data[0].vaild_time;
  } catch (error) {
    console.error('Error fetching movie data:', error);
  }
}

const get_user_pic = async () =>
{
  try {
    const response = await fetch('https://movie.cpb2013.top/account_profile_pic.php?mode=query&key='+user_key.value,{method: 'GET'});
    const data = await response.json();
    console.log(data)
    if (data.status === 'ok') {
      user_info_Data.value['pic']=data.pic;
    }
    console.log(user_info_Data);

  } catch (error) {
    console.error('Error fetching movie data:', error);
  }
}

onMounted(() => {
  isLoggedIn.value = props.key;
  // console.log(props.isLoggedIn);
  check_init();
  // check_init2();
  if(isLoggedIn.value)
  {
    get_user_info();
    get_user_pic()
  }
});

const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

const closeFullScreen = (loading) => {
  loading.close();
};

const logout = () => {
  let loading = openFullScreen();
  const formData = new FormData();
  // Append any form fields you want to send
  formData.append('key',localStorage.getItem('key'));

  fetch('https://movie.cpb2013.top/account.php?mode=logout', {method: 'POST',body:formData})
      .then(response => response.json())
      .then(data => {
        // console.log(data);
        // alert(data.msg);
        localStorage.removeItem('name')
        localStorage.removeItem('key');
        closeFullScreen(loading);
        user_info_Data.value['name']="请先登录";
        user_info_Data.value['money']='';
        user_info_Data.value['last_logout_time']='';
        user_info_Data.value['rank']='';
        user_info_Data.value['vaild_time']='';
        user_info_Data.value['pic']='/nullaccimg.jpg';
        ElMessage({
          type: 'success',
          message: '登出成功',
        })
        router.push('/login');
        isLoggedIn.value=false;
      })
      .catch(error => {
        ElMessage({
          type: 'error',
          message: '登出失败',
        })
        closeFullScreen(loading);
        console.error('登出请求失败:', error);
      });
};

// 监听 localStorage 值的变化
watch(() => localStorage.getItem('key'), (newValue, oldValue) => {
  if (newValue !== oldValue) {
    user_key.value = newValue || ''; // 更新 user_key 值
    isLoggedIn.value = false; // 根据新的 user_key 值更新 isLoggedIn

    // 如果用户已登录，获取更新后的用户信息和图片
    if (isLoggedIn.value) {
      get_user_info();
      get_user_pic();
    } else {
      // 如果用户未登录，将 user_info_Data 重置为默认值
      user_info_Data.value = [{
        name: "请先登录",
        money: '',
        last_logout_time: '',
        rank: '',
        valid_time: '',
        pic: '/nullaccimg.jpg'
      }];
    }
  }
});
</script>

<template>
<view class="W_Account_info_main">
  <view class="W_Account_info_pic">
    <el-image :src="user_info_Data.pic==null?'/nullaccimg.jpg':user_info_Data.pic" style="width: 100px; height: 100px;border-radius: 50px;" fit="cover"/>
  </view>
  <view class="W_Account_info_name">
    {{user_info_Data.name}}
  </view>

  <view class="W_Account_info_level" v-if="isLoggedIn">
    <view class="info">
      <view class="level">
        等级 1
      </view>
      <view class="score">
        30/100
      </view>
    </view>
    <view>
      <el-progress :text-inside="true" :stroke-width="10" :percentage="30" :show-text="false"/>
    </view>
  </view>

  <view class="W_Account_info_vip" v-if="isLoggedIn">
    当前会员：{{user_info_Data.rank==0?"非会员":user_info_Data.rank==1?"普通会员":user_info_Data.rank==2?"超级会员":user_info_Data.rank==3?"super会员":"非会员"}}
  </view>

  <view class="W_Account_info_LookInfo" v-if="isLoggedIn">
    <font-awesome-icon icon="fa-solid fa-hourglass-end" size="2xl" style="color: #c8ecf3;margin-right: 10px"/>{{user_info_Data.rank==0?"无限制":user_info_Data.rank==null?"无限制":user_info_Data.vaild_time}}
  </view>

  <view class="W_Account_info_Money" v-if="isLoggedIn">
    <font-awesome-icon icon="fa-solid fa-sack-dollar" size="lg" style="color: #c8ecf3;margin-right: 10px" />{{user_info_Data.money}}
  </view>

  <view class="W_Account_info_LookInfo" v-if="isLoggedIn">
    <font-awesome-icon icon="fa-solid fa-hourglass-start" size="2xl" style="color: #c8ecf3;margin-right: 10px"/>{{user_info_Data.last_logout_time}}
  </view>
  <view class="logout">
    <el-button type="primary" round v-if="isLoggedIn" @click="logout()">登出</el-button>
  </view>
</view>
</template>

<style scoped>
.W_Account_info_main
{
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  width: 96%;
}
.W_Account_info_pic
{
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  justify-content: center;
  height: 100px;
}
.W_Account_info_name
{
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  justify-content: center;
  color: black;
  font-size: 14px;
  font-weight: 700;
  padding: 10px 0 0 0;
  height: 20px;
}
.W_Account_info_level
{
  margin: 10px 5px 10px 5px;
  width: 100%;
}
.W_Account_info_vip
{
  margin: 10px 5px 10px 5px;
  width: 100%;
  font-weight: 700;
}
.info
{
  display: flex;
  flex-wrap: nowrap;
  flex-direction: row;
  width: 100%;
  height: 20px;
  padding: 10px 0 10px 0;
}
.level
{
  display: flex;
  width: 50%;
  justify-content: left;
}
.score
{
  display: flex;
  width: 50%;
  justify-content: right;
}
.W_Account_info_Money
{
  padding-top: 15px;
  display: flex;
  height: 30px;
  width: 100%;
  padding-left: 10px;
  font-size: 16px;
  font-weight: 800;
}
.W_Account_info_LookInfo

{
  padding-top: 10px;
  display: flex;
  height: 30px;
  width: 100%;
  padding-left: 12px;
  font-size: 10px;
  font-weight: 800;
  align-items: center;
}
.logout
{
  margin-top: 3px;
  display: flex;
  width: 100%;
  justify-content: center;
}
</style>